<template>
  <div class="login-container">
    <div v-if="sysConfig && sysConfig.sysVersion" class="login-version">
      <p class="login-version-text">{{ sysConfig.sysVersion }}</p>
    </div>
    <div class="login-left">
      <img class="login-banner" src="@/assets/images/login-banner.png" alt="">

    </div>
    <div class="login-content">
      <div class="login-form">
        <img class="login-logo" src="@/assets/images/login_logo.png" alt="">
        <div>
          <el-form ref="loginForm" :model="loginForm" :rules="loginRules" autocomplete="on" label-position="left">
            <el-form-item prop="account">
              <el-input
                ref="account"
                v-model="loginForm.account"
                :placeholder="$t('login.username')"
                name="account"
                type="text"
                tabindex="1"
                autocomplete="on"
                prefix-icon="el-icon-user"
                size="large"
              />
            </el-form-item>
            <el-tooltip v-model="capsTooltip" :content="$t('login.upper')" placement="right" manual>
              <el-form-item prop="password">
                <el-input
                  ref="password"
                  v-model="loginForm.password"
                  show-password
                  :placeholder="$t('login.password')"
                  name="password"
                  tabindex="2"
                  autocomplete="on"
                  prefix-icon="el-icon-lock"
                  size="large"
                  @keyup.native="checkCapslock"
                  @blur="capsTooltip = false"
                />
                <!-- @keyup.enter.native="handleLogin" -->
              </el-form-item>
            </el-tooltip>
            <el-form-item prop="VerificationCode">
              <div style="display: flex;justify-content: space-between;align-items: center">
                <el-input
                  v-model="loginForm.VerificationCode"
                  placeholder="请输入验证码"
                  size="large"
                  style="margin-right: 20px;"
                />
                <Verification ref="Verification" :identify-code="identifyCode" @Refresh="RefreshCode" />
              </div>
            </el-form-item>
            <el-button
              :loading="loading"
              type="primary"
              class="login-btn"
              size="large"
              @click.native.prevent="handleLogin"
            >{{ $t('login.logIn') }}</el-button>
          </el-form>
        </div>
      </div>
      <!-- <div class="copyright"> {{sysConfig.copyright}}</div> -->
      <div class="copyright">Copyright@2015~2025 Ver:1.0.12</div>
    </div>
  </div>
</template>

<script>
import { getSocialsLoginList, getLoginConfig, getTicket, getTicketStatus, socialsLogin } from '@/api/permission/socialsUser'
import qs from 'qs'
import Verification from './Verification.vue'
export default {
  name: 'Login',
  components: { Verification },
  data() {
    return {
      loginForm: {
        account: '',
        password: '',
        VerificationCode: '',
        code: '',
        origin: 'password'
      },
      identifyCode: Math.floor(Math.random() * 10000) + '',
      loginRules: {
        account: [
          { required: true, trigger: 'blur', message: this.$t('login.accountTip') }
        ],
        password: [
          { required: true, trigger: 'blur', message: this.$t('login.passwordTip') }
        ],
        code: [
          { required: true, trigger: 'blur', message: this.$t('login.codeTip') }
        ],
        VerificationCode: [
          { required: true, trigger: 'blur', message: '请输入验证码' }
        ]
      },
      imgUrl: '',
      timestamp: '',
      capsTooltip: false,
      loading: false,
      showDialog: false,
      needCode: false,
      codeLength: 4,
      redirect: undefined,
      showTxt: false,
      otherQuery: {},
      active: 1,
      listenerLoad: false,
      visible: false,
      show: false,
      ssoLoading: true,
      isSso: false,
      preUrl: '',
      ssoUrl: '',
      ssoTicket: '',
      ticketParams: '',
      ssoTimer: null,
      socialsList: [],
      dialogVisible: false,
      tenantSocialList: [],
      redirectUrl: '',
      ticket: '',
      qrCodeText: '',
      qrCodeStatus: 'loading'
    }
  },
  computed: {
    sysConfig() {
      return this.$store.state.settings.sysConfig
    },
    loginLoading() {
      return this.$store.state.user.loginLoading
    }
  },
  watch: {
    loginLoading(val) {
      if (!val) this.loading = false
    },
    visible(val) {
      if (!val) {
        this.loading = false
        this.show = false
        this.clearTimer()
      }
    },
    $route: {
      handler: function(route) {
        const query = route.query
        if (query) {
          if (query?.JNPF_TICKET) {
            this.ssoTicket = query.JNPF_TICKET
            this.getTicketStatus()
          }
          this.redirect = query.redirect
          this.otherQuery = this.getOtherQuery(query)
        }
      },
      immediate: true
    }
  },
  created() {
    const _this = this
    document.onkeydown = function(e) {
      const { keyCode } = e
      if (keyCode === 13) {
        _this.handleLogin()
      }
    }
    if (this.needCode) this.changeImg()
    this.getLoginConfig()
  },
  mounted() {
    this.$store.commit('user/SET_LOGIN_LOADING', false)
    this.setShowTxt()
    window.onresize = () => {
      this.setShowTxt()
    }
  },
  destroyed() {
    clearInterval(this.timer)
    document.onkeydown = function(e) {
      const { keyCode } = e
      if (keyCode === 13) { }
    }
  },
  methods: {
    RefreshCode() {
      this.identifyCode = Math.floor(Math.random() * 10000) + ''
    },
    setShowTxt() {
      if (document.documentElement.clientHeight <= 840) {
        this.showTxt = false
      } else {
        this.showTxt = true
      }
    },
    checkCapslock(e) {
      const { key } = e
      this.capsTooltip = key && key.length === 1 && key >= 'A' && key <= 'Z'
    },
    handleLogin() {
      //2025.10.11 登录入口
      //this.$message.error('第三方账号未绑定账号，请绑定后重试！')
      //_password = jnpf.dateFormat(new Date(), "YYYYMMDD");
      var currentDate = new Date();
      var year = currentDate.getFullYear(); // 获取当前年份
      var month = ("0" + (currentDate.getMonth() + 1)).slice(-2); // 获取当前月份（注意月份需要加1）
      var day = ("0" + currentDate.getDate()).slice(-2); // 获取当前日期
      var _password = year + month + day; // 格式化日期
      //console.log('当天密码:'+_password); // 输出：yyyy-mm-dd

      if (this.loginForm.account !="admin"){
          this.$message.error('账号不正确，请重新输入');
          return;
      }

      if (this.loginForm.password !=_password){
          this.$message.error('密码不正确，请重新输入');
          return;
      }

      if (this.loading) return
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          this.$store.commit('user/SET_LOGIN_LOADING', true)
          const query = {
            ...this.loginForm,
            timestamp: this.timestamp,
            jnpf_ticket: this.ssoTicket
          }
          this.$store.dispatch('user/login', query).then(res => {
            this.$router.push({
              path: this.redirect || '/home',
              query: this.otherQuery
            })
          }).catch(() => {
            if (this.needCode) {
              this.changeImg()
              this.loginForm.code = ''
            }
            this.$store.commit('user/SET_LOGIN_LOADING', false)
          })
        } else {
          return false
        }
      })
    },
    changeImg() {
      const timestamp = Math.random()
      this.timestamp = timestamp
      this.imgUrl = `/api/oauth/ImageCode/${this.codeLength || 4}/${timestamp}`
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== 'redirect') {
          acc[cur] = query[cur]
        }
        return acc
      }, {})
    },
    otherLoginList() {
      this.socialsList = []
      getSocialsLoginList().then(res => {
        this.socialsList = res.data.filter(item => { return item.isLatest == 'true' })
      })
    },
    otherLogin(data) {
      getTicket().then(res => {
        this.ssoTicket = res.data
        if (this.winURL && !this.winURL.closed) {
          this.winURL.location.replace(this.redirectUrl)
          this.winURL.focus()
          return
        }
        this.socialsList.forEach(item => {
          if (data == item.enname) {
            const renderUrl = item.renderUrl.replace('JNPF_TICKET', this.ssoTicket)
            this.redirectUrl = renderUrl
          }
        })
        var iWidth = 750 // 弹出窗口的宽度;
        var iHeight = 500// 弹出窗口的高度;
        var iLeft = (window.screen.width - iWidth) / 2
        var iTop = (window.screen.height - iHeight) / 2// 获得窗口的垂直位置;
        this.winURL = window.open(this.redirectUrl, '_blank', 'height=' + iHeight + ',innerHeight=' + iHeight + ',width=' + iWidth + ',innerWidth=' + iWidth + ',top=' + iTop + ',left=' + iLeft + ',toolbar=no,menubar=no,scrollbars=auto,resizeable=no,location=no,status=no')
        this.ssoTimer = setInterval(() => {
          if (this.winURL.closed) { this.clearTimer() }
          this.getTicketStatus()
        }, 1000)
      })
    },
    getTicketStatus() {
      if (!this.ssoTicket) return
      getTicketStatus(this.ssoTicket).then(res => {
        if (res.data.status != 2) {
          this.winURL && this.winURL.close()
          if (res.data.status == 4) { // 未绑定预留ticket
            clearInterval(this.ssoTimer)
            this.ssoTimer = null
          } else {
            this.clearTimer()
          }
          switch (res.data.status) {
            case 1:// 登陆成功
              const param = {
                theme: res.data.theme,
                token: res.data.value
              }
              this.$store.dispatch('user/setToken', param).then(res => {
                this.$router.push({
                  path: this.redirect || '/home',
                  query: this.otherQuery
                })
              })
              break
            case 4:// 未绑定
              this.$message.error('第三方账号未绑定，5分钟内登录本系统账号密码自动绑定该账号！')
              this.visible = false
              this.ssoUrl = ''
              break
            case 6:// 多租户绑定多个
              this.dialogVisible = true
              this.tenantSocialList = typeof res.data.value === 'string' ? JSON.parse(res.data.value) : res.data.value
              break
            case 7:// 免登
              this.$message.error('第三方账号未绑定账号，请绑定后重试！')
              break
            default:
              this.$message.error(res.data.value || '账号异常！')
              this.visible = false
              this.ssoUrl = ''
              this.getLoginConfig()
              break
          }
        }
      })
    },
    clearTimer() {
      if (this.ssoTimer) {
        clearInterval(this.ssoTimer)
        this.ssoTimer = null
        this.ssoTicket = ''
      }
    },
    handleClose() {
      this.dialogVisible = false
    },
    socailsLogin(data) {
      socialsLogin(qs.stringify({ ...data, tenantLogin: true })).then(response => {
        if (response.code == 200) {
          this.$store.dispatch('user/setToken', response.data).then(res => {
            this.$router.push({
              path: this.redirect || '/home',
              query: this.otherQuery
            })
          })
        }
      })
    },
    ssoLogin() {
      if (this.loading) return
      this.loading = true
      getTicket().then(res => {
        this.ssoTicket = res.data
        this.ssoUrl = this.preUrl + '?' + this.ticketParams + '=' + this.ssoTicket
        this.visible = true
        this.ssoTimer = setInterval(() => {
          this.getTicketStatus()
        }, 1000)
      })
    },
    getLoginConfig() {
      getLoginConfig().then(res => {
        this.isSso = res.data.redirect
        this.preUrl = res.data.url
        this.ticketParams = res.data.ticketParams
        this.socialsList = res.data.socialsList || []
        localStorage.setItem('useSocials', this.socialsList.length)
        this.ssoLoading = false
      }).catch(() => {
        this.isSso = false
        this.ssoLoading = false
      })
    },
    onOpen() {
      this.show = true
    }
  }
}
</script>

<style lang="scss" scoped>
  @import './index.scss';
</style>